package com.yc.jpyy.wxuser.service.impl;

import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.service.BaseService;
import com.yc.jpyy.wxuser.dao.WxUserDao;
import com.yc.jpyy.wxuser.service.WxUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class WxUserServiceImpl extends BaseService implements WxUserService {

    @Autowired
    private WxUserDao wxUserDao;
    @Override
    public Map<String,Object> getDriver(Map<String, Object> paramsMap) {
        return this.wxUserDao.getDriver(paramsMap);
    }

    @Override
    public void add(Map<String, Object> paramsMap) {
        this.wxUserDao.add(paramsMap);
    }

    @Override
    public void update(Map<String, Object> paramsMap) {
        this.wxUserDao.update(paramsMap);
    }

    @Override
    public Map<String, Object> findById(Map<String, Object> paramsMap) {
        return this.wxUserDao.findById(paramsMap);
    }

	@Override
	public Map<String, Object> getWxUserList(Map<String, Object> paramsMap)
			throws DataAccessException {
		Map<String,Object> resultMap = new HashMap<>();
		int pagenum = Integer.parseInt(paramsMap.get("pagenum").toString());
		int pagesize = Integer.parseInt(paramsMap.get("pagesize").toString());
		paramsMap.put("pagestart", (pagenum-1) * pagesize);
		List<Map<String,Object>> wxUserList = wxUserDao.getWxUserList(paramsMap);
		int wxUserCounts = wxUserDao.selectwxUserCount(paramsMap);
		if(wxUserList != null && wxUserList.size() > 0){
			resultMap.put("returnCode", 1);
			resultMap.put("ListData",wxUserList);
			resultMap.put("TotalCount",wxUserCounts);
			resultMap.put("TotalPage",wxUserCounts % pagesize >0 ? wxUserCounts/pagesize + 1 : wxUserCounts/pagesize);
			resultMap.put("returnMsg", "操作成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "系统无数据");
		}
		return resultMap;
	}



	@Override
	public Map<String, Object> checkIsBind(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		//根据openID查询记录，不存在，则未绑定
		Map<String,Object> map = wxUserDao.getInfoByOpenID(paramsMap);
		if(map != null && map.size() > 0){
			if(paramsMap.get("utype").toString().equals("1")){
				//根据utype类型查看，如果是车主，则要检查openid对应的记录utype类型是否为车主，如果不是，则说明车主未绑定
				String utype = Optional.ofNullable(map.get("utype")).orElse("").toString();
				if(!utype.equals("1")){
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "该用户未绑定");
					return resultMap;
				}else{
					//检查联系电话和身份号是否存在
					resultMap = checkIsHaveInfo(map);
				}
			}else if(paramsMap.get("utype").toString().equals("2")){
				//检查联系电话和身份号是否存在
				resultMap = checkIsHaveInfo(map);
			}else if(paramsMap.get("utype").toString().equals("3")){
				//如果类型为3，则检查UserId是否存在（并且判断是否是执法人员以及是否已删除）
				String userId = Optional.ofNullable(map.get("userId")).orElse("").toString();
				if(userId.isEmpty() || userId.equals("")){
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "该用户未绑定");
					return resultMap;
				}else{
					paramsMap.put("userid", userId);
					//根据userId查询用户PIUSER表中的yuliu2字段（代表权限）
					Map<String,Object> maps =  wxUserDao.selectYuliu2(paramsMap);
					if(maps != null && maps.size() > 0){
						//是否执法人员 0否，1是，默认0
						String yuliu2 = maps.get("yuliu2").toString();
						//是否删除
						String isDelete = maps.get("DELETEMARK").toString();
						if(yuliu2.isEmpty() || yuliu2.equals("")){
							resultMap.put("returnCode", 0);
							resultMap.put("returnMsg", "该用户无任何权限");
							return resultMap;
						}else if(!yuliu2.isEmpty() && !yuliu2.equals("") && !yuliu2.equals("1")){
							resultMap.put("returnCode", 0);
							resultMap.put("returnMsg", "该用户不是执法人员");
							return resultMap;
						}else if(!isDelete.isEmpty() && !isDelete.equals("") && !isDelete.equals("0")){
							resultMap.put("returnCode", 0);
							resultMap.put("returnMsg", "该用户已删除");
							return resultMap;
						}else{
							map.put("yuliu2", yuliu2);
							resultMap.put("returnCode", 1);
							resultMap.put("returnMsg", "该用户已绑定");
							resultMap.put("ListData", map);
						}
					}
				}
			}
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "该用户未绑定");
		}
		return resultMap;
	}
	
	
	/*
	 * 检查联系电话和身份号是否存在
	 */
	public Map<String, Object> checkIsHaveInfo(Map<String, Object> map)
			throws DataAccessException {
		Map<String,Object> resultMap = new HashMap<>();
		//记录存在的情况下，查询driver，driver,未存在，则未绑定
		String lxrPhone = Optional.ofNullable(map.get("lxrPhone")).orElse("").toString();
		String idNumber = Optional.ofNullable(map.get("idNumber")).orElse("").toString();
		if(lxrPhone != null && !lxrPhone.isEmpty() && !lxrPhone.equals("")
				&&  idNumber != null && !idNumber.isEmpty() && !idNumber.equals("")){
			//绑定了，则返回手机号和身份证号
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "该用户已绑定");
			resultMap.put("ListData", map);
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "该用户未绑定");
		}
		return resultMap;
	}
	
	
	@Override
	public Map<String, Object> addBind(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		String utype = paramsMap.get("utype").toString();
		if(utype.equals("1")){
			//根据身份证号和号码在Vehicle表中查询该车主是否存在
			List<Map<String,Object>> vCount = wxUserDao.getDriverByIdCard(paramsMap);
			if(vCount != null && vCount.size() > 0){
				//绑定
				List<String> list = vCount.stream().map(map->map.get("dbcode").toString()).collect(Collectors.toList());
				String dbcode =  String.join(",", list);
				paramsMap.put("dbcode",dbcode);
				resultMap = this.addBindForWxuser(paramsMap);
			}else{
				resultMap.put("returnCode", 0);
				resultMap.put("returnMsg", "不存在该车主信息");
			}
		}else if(utype.equals("2")) {
			//直接绑定
			resultMap = this.addBindForWxuser(paramsMap);
		}else if(utype.equals("3")) {
			//根据用户名和密码检查用户是否,如果存在则获取userid
			 List<Map<String,Object>> user = wxUserDao.getUserId(paramsMap);
			if(user != null && user.size() > 0){
				//是否执法人员 0否，1是，默认0
				String yuliu2 = user.get(0).get("yuliu2").toString();
				//是否删除
				String isDelete = user.get(0).get("DELETEMARK").toString();
				if(yuliu2.isEmpty() || yuliu2.equals("")){
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "该用户无任何权限");
					return resultMap;
				}else if(!yuliu2.isEmpty() && !yuliu2.equals("") && !yuliu2.equals("1")){
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "该用户不是执法人员");
					return resultMap;
				}else if(!isDelete.isEmpty() && !isDelete.equals("") && !isDelete.equals("0")){
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "该用户已删除");
					return resultMap;
				}
				//绑定
				paramsMap.put("userid", user.get(0).get("Id"));
				List<String> list = user.stream().map(map->map.get("dbcode").toString()).collect(Collectors.toList());
				String dbcode =  String.join(",", list);
				paramsMap.put("dbcode",dbcode);
				resultMap = this.addBindForWxuser(paramsMap);
			}else{
				resultMap.put("returnCode", 0);
				resultMap.put("returnMsg", "用户名或密码错误");
			}
		}	
		return resultMap;
	}
	
	/*
	 * 实现绑定
	 */
	public Map<String, Object> addBindForWxuser(Map<String, Object> paramsMap)
			throws DataAccessException {
		Map<String,Object> resultMap = new HashMap<>();
		//先查询用户是否已经绑定在其他微信用户账号上
		int isBindOther = wxUserDao.checkIsBindOther(paramsMap);
		if(isBindOther > 0){
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "该用户已绑定在其他微信账户中");
		}else{
			//根据openID查询记录，不存在，新增记录
			Map<String,Object> map = wxUserDao.getInfoByOpenID(paramsMap);
			if(map != null && map.size() > 0){
				//存在记录，绑定电话，就是把电话号码更新到记录中
				int counts = wxUserDao.updateBindWxuser(paramsMap);
				if(counts > 0){
					resultMap.put("returnCode", 1);
					resultMap.put("returnMsg", "绑定成功");
					resultMap.put("ListData", Optional.ofNullable(paramsMap.get("dbcode")).orElse(""));
				}else{
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "绑定失败");
				}
			}else{
				int count = wxUserDao.addBindForWxuser(paramsMap);
				if(count > 0){
					resultMap.put("returnCode", 1);
					resultMap.put("returnMsg", "绑定成功");
					resultMap.put("ListData", Optional.ofNullable(paramsMap.get("dbcode")).orElse(""));
				}else{
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "绑定失败");
				}
			}	
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> updateWxUserBlack(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		paramsMap.put("ids", paramsMap.get("ids").toString().split(","));
		int count = wxUserDao.updateWxUserBlack(paramsMap);
		if(count > 0){
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "修改成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "修改失败");
		}
		return resultMap;
	}

	@Override
	public RestResponse addWxGongzhonghaoService(RestResponse response,Map<String, Object> paramsMap) throws DataAccessException {
		int count = wxUserDao.findwxUserCountByOpenIdDao(paramsMap);
		if(count == 0) {
			int i = wxUserDao.add(paramsMap);
			if (i > 0 ){
				response.setReturnCode(1);
				response.setReturnMsg("添加成功");
			}else{
				response.setReturnCode(0);
				response.setReturnMsg("添加失败");
			}
		}else {
			int k = wxUserDao.updateGuanZhuWxuser(paramsMap);
			if (k > 0 ){
				response.setReturnCode(1);
				response.setReturnMsg("添加成功");
			}else{
				response.setReturnCode(0);
				response.setReturnMsg("添加失败");
			}
		}
		return response;
	}
	
	@Override
	public int updateGuanZhuWxuserQXService(Map<String, Object> paramsMap) throws DataAccessException {
		return wxUserDao.updateGuanZhuWxuserQX(paramsMap);
	}


	@Override
	public Map<String, Object> getVehicleInfo(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		int pagenum = Integer.parseInt(paramsMap.get("pagenum").toString());
		int pagesize = Integer.parseInt(paramsMap.get("pagesize").toString());
		paramsMap.put("pagestart", (pagenum-1) * pagesize);
		List<Map<String,Object>> listMap = wxUserDao.getVehicleInfo(paramsMap);
		int counts = wxUserDao.getVehicleCount(paramsMap);
		if(listMap != null && listMap.size() > 0){
			listMap.stream().forEach(map -> {
				paramsMap.put("id",map.get("VehicleId"));
				paramsMap.put("dbcode",map.get("dbcode"));
				map.put("driverInfo", wxUserDao.getDriverInfoByVehicleId(paramsMap));
			});
			resultMap.put("returnCode", 1);
			resultMap.put("pageNum", paramsMap.get("pagenum"));
			resultMap.put("ListData",listMap);
			resultMap.put("TotalCount",counts);
			resultMap.put("TotalPage",counts % pagesize >0 ? counts/pagesize + 1 : counts/pagesize);
			resultMap.put("returnMsg", "操作成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "系统无数据");
		}
		return resultMap;
	}
	

	@Override
	public Map<String, Object> getDriverInfo(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		int pagenum = Integer.parseInt(paramsMap.get("pagenum").toString());
		int pagesize = Integer.parseInt(paramsMap.get("pagesize").toString());
		paramsMap.put("pagestart", (pagenum-1) * pagesize);
		List<Map<String,Object>> listMap = wxUserDao.getDriverInfo(paramsMap);
		int counts = wxUserDao.getDriverCount(paramsMap);
		if(listMap != null && listMap.size() > 0){
			listMap.stream().forEach(map -> {
				paramsMap.put("id",map.get("DriverId"));
				paramsMap.put("dbcode",map.get("dbcode"));
				map.put("vehicleInfo", wxUserDao.getVehicleInfoByDriverIds(paramsMap));
			});
			resultMap.put("returnCode", 1);
			resultMap.put("pageNum", paramsMap.get("pagenum"));
			resultMap.put("ListData",listMap);
			resultMap.put("TotalCount",counts);
			resultMap.put("TotalPage",counts % pagesize >0 ? counts/pagesize + 1 : counts/pagesize);
			resultMap.put("returnMsg", "操作成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "系统无数据");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> getVehicleInfoById(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		Map<String,Object> map = wxUserDao.getVehicleInfoById(paramsMap);
		if(map != null && map.size() > 0){
			map.put("driverInfo", wxUserDao.getDriverInfoByVehicleId(paramsMap));
			resultMap.put("returnCode", 1);
			resultMap.put("ListData",map);
			resultMap.put("returnMsg", "操作成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "系统无数据");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> getDriverInfoById(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		Map<String,Object> map = wxUserDao.getDriverInfoById(paramsMap);
		if(map != null && map.size() > 0){
			map.put("vehicleInfo", wxUserDao.getVehicleInfoByDriverId(paramsMap));
			resultMap.put("returnCode", 1);
			resultMap.put("ListData",map);
			resultMap.put("returnMsg", "操作成功");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "系统无数据");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> checkOpenidIsExist(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<>();
		int count = wxUserDao.checkOpenidIsExist(paramsMap);
		if(count > 0){
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "该用户已关注");
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "该用户未关注");
		}
		return resultMap;
	}
}
